from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.core.urlresolvers import reverse


from common.models import Types, Goods

# 公共信息加载函数


def loadinfo(request):
    '''加载商品类别信息'''
    lists = Types.objects.filter(pid=0)
    context = {'typelist': lists}
    return context


def index(request):
    '''浏览购物车'''
    context = loadinfo(request)
    if 'shoplist' not in request.session:
        request.session['shoplist'] = {}
    return render(request, "web/cart.html", context)


def add(request, gid):
    '''添加购物车'''
    goods = Goods.objects.get(id=gid)
    shop = goods.toDict()
    # toDict()是Goods类中自定义的信息输出方法
    # goods是Goods类的实例化对象,若无toDict()则拿不到商品的信息,如价格`名称等等,只能拿到字段名信息
    shop['m'] = int(request.POST.get("m", 1))
    # 商品对象中原本并没有购买数量m这个属性,但是记住字典有则加进去,无则创建然后加进去
    shoplist = request.session.get("shoplist", {})
    # 第一次进来购物车的时候什么都没有,默认值是{},空
    #往下走执行shoplist[gid] = shop

    # 判断购物车中是否已存在要购买的商品
    if gid in shoplist:
        shoplist[gid]['m'] += shop['m']  # 累加购买量
    else:
        shoplist[gid] = shop
    # 将购物车中的商品信息放回到session中
    request.session['shoplist'] = shoplist
    # 放回session中其实是放回了数据库中,保存起来了信息,别的函数也能直接访问的调用里面的信息了

    # 跳转查看购物车
    return redirect(reverse('cart_index'))


def delete(request, gid):
    '''删除购物车中的商品'''
    shoplist = request.session['shoplist']
    del shoplist[gid]
    request.session['shoplist'] = shoplist
    return redirect(reverse('cart_index'))


def clear(request):
    '''清空购物车'''
    request.session['shoplist'] = {}
    return redirect(reverse('cart_index'))


def change(request):
    '''购物车信息修改'''
    shoplist = request.session['shoplist']
    #<input class="mz-adder-input" value="{{ shop.m }}" onblur="window.location='{% url 'cart_change' %}?gid={{shop.id}}&num='+this.value" type="text">
    # 不如理解成一种走肾不走心的参数传递的方法,纠结个屁,一样的传递参数,不过是不走路由,函数也不用接收罢了

    shopid = request.GET.get("gid", 0)
    num = int(request.GET.get('num', 1))
    if num < 1:
        num = 1
    shoplist[shopid]['m'] = num
    request.session['shoplist'] = shoplist
    return redirect(reverse('cart_index'))
